package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceReportDataVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 设备信息Service业务层处理
 * 
 * @author ZHD
 * @date 2025-08-21
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备信息
     * 
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备信息列表
     * 
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     * 
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备信息
     * 
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备信息
     * 
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息信息
     * 
     * @param iotId 设备id
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDeviceById(String iotId)
    {
        remove(new LambdaQueryWrapper<Device>().eq(Device::getIotId,iotId));
        DeleteDeviceRequest request=new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(request);
        if (deleteDeviceResponse.getHttpStatusCode() !=204){
            throw new BaseException("删除设备失败");
        }
        return 1;
    }

    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse listProductsResponse = client.listProducts(request);
        if (listProductsResponse.getHttpStatusCode() !=200){
            throw new BaseException("同步产品列表失败");
        }
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(listProductsResponse.getProducts()));
    }

    @Override
    public List<ProductVo> allProduct() {
        String jsonStr= (String)redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if(StringUtils.isEmpty(jsonStr)){
            return new ArrayList<>();
        }
        return JSONUtil.toList(jsonStr,ProductVo.class);
    }

    /**
     * 注册设备
     * @param deviceDto 设备信息
     */
    @Override
    public void register(DeviceDto deviceDto) {
        //1.判断设备名称是否重复
          isExistDeviceName(deviceDto.getDeviceName());
        //2判断设备标识符是否重复
          isExistNodeId(deviceDto.getNodeId());
        //3.判断同一位置是否绑定了相同的设备
        if(Objects.isNull(deviceDto.getDeviceDescription())){
            deviceDto.setPhysicalLocationType(-1);
        }
          isExistBindingLocation(deviceDto);
        //4.在华为IOT平台上注册设备
        AddDeviceResponse response = enrollDevice(deviceDto);
        //5.在本地数据库保存数据
        saveDevice(deviceDto,response);
    }

    /**
     * 根据设备id查询设备详情
     * @param id 设备id
     * @return 设备详情
     */
    @Override
    public DeviceDetailVo findDeviceById(String id) {
        //1.在IOT平台上查询设备信息
        ShowDeviceRequest request=new ShowDeviceRequest();
        request.withDeviceId(id);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() !=200){
            throw new BaseException("查询设备信息失败");
        }
        String status = response.getStatus();
        String time = response.getActiveTime();
        //2.在数据库查询设备信息
        Device device = this.lambdaQuery()
                .eq(Device::getIotId, id)
                .one();
         if (Objects.isNull(device)){
             throw new BaseException("设备不存在");
         }
        //3.封装数据并返回
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
         deviceDetailVo.setDeviceStatus(status);
        if(StringUtils.isNotEmpty(time)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(time, DatePattern.UTC_MS_PATTERN);
            activeTime=activeTime.atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    /**
     * 查询设备上报数据
     * @param iotId 设备ID
     * @return 设备上报数据
     */
    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {
        ArrayList<DeviceReportDataVo> voList = new ArrayList<>();
        try {
            ShowDeviceShadowRequest request=new ShowDeviceShadowRequest();
            request.withDeviceId(iotId);
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);
            if (response.getHttpStatusCode() !=200){
                throw new BaseException("查询设备信息失败");
            }
            List<DeviceShadowData> list = response.getShadow();
            if(CollUtil.isEmpty(list)){
                return voList;
            }
            list.forEach(item -> {
                String eventTimeStr = item.getReported().getEventTime();
                Map<String, Object> map = (Map<String, Object>) item.getReported().getProperties();
                map.forEach((k,v)->{
                  LocalDateTime eventTime=null;
                  if(StringUtils.isNotEmpty(eventTimeStr)){
                      eventTime = LocalDateTimeUtil.parse(eventTimeStr, Constants.LOCAL_DATE_TIME_FORMATTER)
                              .atZone(ZoneId.of("Asia/Shanghai"))
                              .toLocalDateTime();
                  }
                    DeviceReportDataVo vo = DeviceReportDataVo.builder()
                            .functionId(k)
                            .eventTime(eventTime)
                            .value(v)
                            .build();
                  voList.add(vo);
                });
            });
        } catch (BaseException e) {
            throw new BaseException("查询设备上报数据失败");
        }
        return voList;
    }



    /**
     * 本地数据库保存数据
     * @param deviceDto 设备信息
     * @param response 注册结果
     */
    private void saveDevice(DeviceDto deviceDto, AddDeviceResponse response) {
        Device device = new Device();
        if(deviceDto.getPhysicalLocationType().equals(-1)){
            device.setHaveEntranceGuard(0);
        }else {
            device.setHaveEntranceGuard(1);
        }
        BeanUtil.copyProperties(deviceDto,device);
        device.setIotId(response.getDeviceId());
        device.setSecret(response.getAuthInfo().getSecret());
        save(device);
    }

    /**
     * 华为云设备注册
     * @param deviceDto 设备信息
     * @return 注册结果
     */
    private AddDeviceResponse enrollDevice(DeviceDto deviceDto) {
        AddDeviceRequest request=new AddDeviceRequest();
        AddDevice body=new AddDevice();
        AuthInfo authInfo=new AuthInfo();
        String code = UUID.randomUUID().toString();
        String UUID = code.replaceAll("-", "");
        authInfo.withAuthType("SECRET")
                .withSecret(UUID)
                .withSecureAccess(true);
        body.withDeviceId(deviceDto.getNodeId())
                .withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey())
                .withNodeId(deviceDto.getNodeId())
                .withAuthInfo(authInfo);
        request.withBody(body);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() !=201){
            throw new BaseException("设备注册失败");
        }
        return response;
    }

    private void isExistBindingLocation(DeviceDto deviceDto) {
        //1.判断是否是同一种设备
        Long count = this.lambdaQuery().eq(Device::getProductKey, deviceDto.getProductKey())
                //2.判断是否是同一种位置
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                //3.判断是否是同种位置类型
                .eq(Device::getLocationType, deviceDto.getLocationType())
                //4.判断是否是同种物理位置类型
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
          if (count > 0){
              throw new BaseException("同一位置已绑定了相同的设备");
          }
    }
    /**
     * 判断设备标识符是否存在
     * @param nodeId 注册设备的标识符
     */
    private void isExistNodeId(String nodeId) {
        if(this.lambdaQuery().eq(Device::getNodeId, nodeId)
                .count()>0){
            throw new BaseException("设备标识符已存在");
        }
    }

    /**
     * 判断设备名称是否重复
     * @param deviceName 注册设备名称
     */
    private void isExistDeviceName(String deviceName) {
        if (this.lambdaQuery().eq(Device::getDeviceName, deviceName)
                .count()>0){
            throw new BaseException("设备名称已存在");
        }
    }

    /**
     * 注册设备
     * @param deviceDto 设备信息
     */
    @Override
    @Transactional
    public void updateDeviceAndIot(DeviceDto deviceDto) {
        //判断是否修改产品Id
        Device deviceDb = this.selectDeviceById(deviceDto.getId());
        if(!deviceDb.getProductKey().equals(deviceDto.getProductKey())){
            register(deviceDto);
            return;
        }
        //1.修改本地
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        deviceMapper.updateDevice(device);
        //2.修改华为云IOT
        UpdateDeviceRequest request=new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice body=new UpdateDevice();
        AuthInfoWithoutSecret authInfo=new AuthInfoWithoutSecret();
        authInfo.withSecureAccess(true);
        body.withDeviceName(deviceDto.getProductName())
                .withAuthInfo(authInfo);
        request.withBody(body);
        UpdateDeviceResponse updateDeviceResponse = client.updateDevice(request);
        if (updateDeviceResponse.getHttpStatusCode() !=200){
            throw new BaseException("修改设备信息失败");
        }
    }

    /**
     * 查询产品信息
     * @param productKey 产品key
     * @return 产品信息
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request=new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() !=200){
            throw new BaseException("查询产品信息失败");
        }
        return response.getServiceCapabilities();
    }


}

